package com.code.bolg.controller;

import com.code.bolg.annotation.ReturnParam;
import com.code.bolg.bean.Comment;
import com.code.bolg.bean.User;
import com.code.bolg.constant.CookieConstant;
import com.code.bolg.constant.RedisConstant;
import com.code.bolg.constant.ServletPath;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.service.UserService;
import com.code.bolg.utils.ApiReturnUtil;
import com.code.bolg.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public Object login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response, HttpServletRequest request) {
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        User user = userService.find(u);
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (user == null) {
            return  ResultEnum.NOTFINDUSER;
        }

        //针对已登录用户
        String format = String.format(RedisConstant.TOKEN_TEMPLATE, cookie==null?null:cookie.getValue());
        String redisId = stringRedisTemplate.opsForValue().get(format);

        //用户名正确，redis没有存储
        if (user != null && redisId == null) {
            //cookie里设置token=UUID, redis设置key=UUID, value=xyz
            String token = UUID.randomUUID().toString();
            String key = String.format(RedisConstant.TOKEN_TEMPLATE, token);
            Integer expier = CookieConstant.expier;
            stringRedisTemplate.opsForValue().set(key, user.getUserId().toString(), expier, TimeUnit.SECONDS);
            //cookie里设置token
            CookieUtil.set(response, CookieConstant.TOKEN, token, CookieConstant.expier);
            return HttpStatus.OK.name();
        }


        //访问的是/login ，cookie!=null,redis的value===user.getId
        if (ServletPath.loginPath.equals(request.getServletPath()) && cookie != null && user != null && user.getUserId().toString().equals(redisId)) {
            return ResultEnum.LOGINED.getMessage();
        }

        return HttpStatus.OK.name();
    }

    @RequestMapping("/getUserName")
    @ReturnParam(isEnum=true)
    public Object getUserName(HttpServletRequest request) {
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie==null){
            return ResultEnum.NOTLOGIN;
        }


        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        String userId = stringStringValueOperations.get(String.format(RedisConstant.TOKEN_TEMPLATE, cookie.getValue()));

        if(StringUtils.isEmpty(userId)){
            return ResultEnum.FAILURELOG;
        }


        //访问的是/login ，cookie!=null,redis有cookie对应记录
        if (cookie != null && !StringUtils.isEmpty(userId)) {
            User user = userService.findById(Integer.valueOf(userId));
            return user.getUsername();
        }

        return ResultEnum.NOTLOGIN;
    }


}
